package com.zhengbing.tj.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhengbing.tj.entity.LoginRecord;
import com.zhengbing.tj.mapper.LoginRecordMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import java.time.LocalDateTime;
import com.zhengbing.tj.service.LoginRecordService;
import org.springframework.stereotype.Service;


/**
 * 登录记录服务实现类
 * 处理用户登录登出记录的具体业务逻辑
 * @author zhengbing
 * @date 2025-07-25
 */
@Service
public class LoginRecordServiceImpl extends ServiceImpl<LoginRecordMapper, LoginRecord> implements LoginRecordService {

    @Override
    public Long recordLogin(Long userId, String ipAddress, String deviceInfo) {
        LoginRecord loginRecord = new LoginRecord();
        loginRecord.setUserId(userId);
        loginRecord.setLoginTime(LocalDateTime.now());
        loginRecord.setIpAddress(ipAddress);
        loginRecord.setDeviceInfo(deviceInfo);
        // 0表示登录中
        loginRecord.setStatus(0);
        // 根据错误提示，LoginRecord 类没有 setIpLocation 方法，推测可能的正确方法名，这里假设为 setLocation 方法
        loginRecord.setLocation(getLocationByIp(ipAddress));
        save(loginRecord);
        // 返回登录记录ID
        return loginRecord.getId();
    }

    @Override
    public void recordLogout(Long userId) {
        // 查询用户最新未登出的登录记录
        LoginRecord latestLogin = getOne(Wrappers.lambdaQuery(LoginRecord.class)
                .eq(LoginRecord::getUserId, userId)
                .isNull(LoginRecord::getLogoutTime)
                .orderByDesc(LoginRecord::getLoginTime)
                .last("LIMIT 1"));
        
        if (latestLogin != null) {
            latestLogin.setLogoutTime(LocalDateTime.now());
        // 1表示已登出
        latestLogin.setStatus(1);
            updateById(latestLogin);
        }
    }

    /**
     * 简单模拟根据IP获取地理位置
     * 实际项目中可集成IP定位服务
     */
    @Override
    public LoginRecord getLoginRecordById(Long recordId) {
        return getById(recordId);
    }

    @Override
    public LoginRecord getLatestLoginRecordByUserId(Long userId) {
        return getOne(Wrappers.lambdaQuery(LoginRecord.class)
                 .eq(LoginRecord::getUserId, userId)
                 .orderByDesc(LoginRecord::getLoginTime)
                 .last("LIMIT 1"));
    }

    @Override
    public boolean updateStatusByUserId(Long userId, Integer status) {
        LambdaUpdateWrapper<LoginRecord> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(LoginRecord::getUserId, userId)
                     .set(LoginRecord::getStatus, status)
                     .set(LoginRecord::getLogoutTime, LocalDateTime.now());
        return update(updateWrapper);
    }

    private String getLocationByIp(String ipAddress) {
        // 简单模拟IP定位
        return "未知位置"; // 实际项目中可集成IP定位服务
    }
}